#include "player.h"

#include <boost/foreach.hpp>

#include "interfaces/audio_sink_interface.h"
#include "interfaces/audio_source_interface.h"
#include "types.h"

using namespace pita;

#define LOCK() boost::recursive_mutex::scoped_lock lock(mutex_);

namespace
{

	unsigned int cTimeout = 100;
	
}

Player::~Player()
{
	shutdown();
	thread_.join();
}

void Player::play()
{
	LOCK();

	playing_ = true;
	playSignal();
	condition_.notify_one();
}

void Player::pause()
{
	LOCK();

	playing_ = false;
	pauseSignal();
	condition_.notify_one();
}

bool Player::playing() const
{
	LOCK();

	return playing_;
}

void Player::shutdown()
{
	LOCK();
	running_ = false;
	condition_.notify_one();
}

void Player::playFunc()
{
	DataChunk chunk(4096);

	while (true)
	{
		{ // Only hold lock long enough to check that we should be playing something
			LOCK();
			
			while (!playing() && running_)
				condition_.wait(lock);

			if (!running_) break;
		}

		chunk.resize(4096);

		if (source_->nextChunk(chunk, ::cTimeout))
		{
			BOOST_FOREACH(AudioSinkInterface* sink, sinks_)
			{
				sink->play(chunk);
			}
		}
	}
}
